package com.jxb.myshop.web.servlet;

import com.jxb.myshop.common.Constant;
import com.jxb.myshop.common.ResponseResult;
import com.jxb.myshop.entity.User;
import com.jxb.myshop.services.CartServices;
import com.jxb.myshop.services.impl.CartServicesImpl;
import com.jxb.myshop.util.StringUtil;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/cart")
public class CartController extends BaseController {
    private CartServices cs = new CartServicesImpl();

    /**
     * 更新购物车商品数量
     */
    public String updateCartNum(HttpServletRequest request, HttpServletResponse response){
        User user = (User) request.getSession().getAttribute(Constant.SystemConstant.IS_LOGIN);
        if (user == null){
            return Constant.Re.URL_REDIRECT + "/login.jsp";
        }
        int pid = StringUtil.StringToInt(request.getParameter("pid"));
        int num = StringUtil.StringToInt(request.getParameter("num"));
        ResponseResult rr = cs.updateCartNum(user.getUid(),pid,num);
        //因为 这个前端设置的是ajax而且自己进行了前端的重新发送请求,所以不需要给响应数据
        // 所以返回空字符串
        return "";
    }

    /**
     * 清除购物车全部数据,以及清除单条数据
     */
    public String clearCart(HttpServletRequest request, HttpServletResponse response){
        User user = (User) request.getSession().getAttribute(Constant.SystemConstant.IS_LOGIN);
        if (user == null){
            return Constant.Re.URL_REDIRECT + "/login.jsp";
        }
        int pid = StringUtil.StringToInt(request.getParameter("pid"));
        ResponseResult rr = cs.clearCart(user.getUid(),pid);
        request.setAttribute("rr",rr);
        return Constant.Re.URL_FORWARD + "message.jsp";
    }

    /**
     * 新增购物车
     */
    public String addCart(HttpServletRequest request, HttpServletResponse response){
        User user = (User) request.getSession().getAttribute(Constant.SystemConstant.IS_LOGIN);
        if (user == null){
            return Constant.Re.URL_REDIRECT + "/login.jsp";
        }
        int pid = StringUtil.StringToInt(request.getParameter("pid"));
        ResponseResult rr = cs.createCart(user.getUid(),pid);
        request.getSession().setAttribute("rr",rr);
        return Constant.Re.URL_FORWARD + "/cartSuccess.jsp";
    }

    /**
     * 获取购物车中的数据
      */
    public String getCart(HttpServletRequest request, HttpServletResponse response){
        User user = (User) request.getSession().getAttribute(Constant.SystemConstant.IS_LOGIN);
        // 判断用户是否登录
        if (user == null) {
            return Constant.Re.URL_REDIRECT + "/login.jsp";
        }
        ResponseResult rr = cs.getCartList(user.getUid());
        request.setAttribute("rr",rr);
        return Constant.Re.URL_FORWARD + "/cart.jsp";
    }
}
